package com.zangchat.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.core.domain.AjaxResult;
import com.common.utils.StringUtils;
import com.zangchat.utils.Md5Utils;
import com.zangchat.utils.RedisUtil;
import com.zangchat.utils.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;

@Controller
public class AppController {
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/api/app")
    public String toRediRect(@RequestBody(required = true) Map<String, Object>  map, RedirectAttributes model) {
        String code = (String) map.get("code");
        code = code.replace("-", "/");
        code = "zangchat/" + code;
        if (map.get("data").toString().equals("")){
            map.put("data","[]");
        }
        //通用参数的校验
        if (StringUtils.isNull(map.get("sign"))||StringUtils.isNull(map.get("derviceId"))||StringUtils.isNull(map.get("timestamp"))){
            return "ERROR";
        }
        /**
         * 进行MD5校验接口
         */
        Md5Utils md5Utils=new Md5Utils();
        boolean result = md5Utils.checkAppInterface(map.get("sign").toString(), map.get("derviceId").toString(), map.get("timestamp").toString());
        if (!result){
            return "ERROR";
        }
        if(!map.get("data").toString().equals("[]")){
            JSONObject data = JSONObject.parseObject(map.get("data").toString());
            if (StringUtils.isNotNull(data.get("userId"))){
                //判断账号是否被顶下
                boolean resultBoolean = redisUtil.checkUserId(Long.valueOf(data.get("userId").toString()), map.get("derviceId").toString());
                if (!resultBoolean){
                    AjaxResult ajax=AjaxResult.displacementUser();
                    return ajax.toString();
                }
            }
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                Object value = entry.getValue();
                if(value instanceof JSONArray){
                    String s = ((JSONArray) value).toJSONString();
                    value =s ;
                }
                model.addAttribute(entry.getKey(),value);
            }
        }
        return "redirect:/"+code;
    }

}
